package gui.windows.components;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;

import cardmanager.CardInfo;
import cardmanager.CardManager;
import cardmanager.enums.CardType;

import app.AppGlobals;
import javax.swing.JList;

@SuppressWarnings("serial")
public class DeckPanel extends JPanel {
	JLabel cardImage;
	JLabel cardName;
	JTextPane cardText;
	CardList mainDeck;
	private JLabel lblMainDeck;
	private JLabel lblSideDeck;
	private JScrollPane scrollPane_2;
	private CardList sideDeck;
	private JScrollPane scrollPane_3;
	private CardList extraDeck;
	private JLabel lblExtraDeck;
	public DeckPanel(){
		this.setBorder(new LineBorder(new Color(0, 0, 0)));
		this.setBounds(429, 22, 476, 348);
		this.setLayout(null);
		

		cardImage = new JLabel();
		cardImage.setBounds(279, 11, 187, 224);
		this.add(cardImage);
		
		cardName = new JLabel("Card Name");
		cardName.setBounds(241, 238, 225, 14);
		this.add(cardName);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(241, 256, 225, 81);
		this.add(scrollPane);
		
		cardText = new JTextPane();
		cardText.setEditable(false);
		scrollPane.setViewportView(cardText);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(10, 27, 210, 98);
		this.add(scrollPane_1);
		
		mainDeck = new CardList();
		scrollPane_1.setViewportView(mainDeck);
		
		lblMainDeck = new JLabel("Main Deck");
		lblMainDeck.setBounds(10, 11, 210, 14);
		add(lblMainDeck);
		
		lblSideDeck = new JLabel("Side Deck");
		lblSideDeck.setBounds(10, 238, 46, 14);
		add(lblSideDeck);
		
		scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(10, 256, 210, 81);
		add(scrollPane_2);
		
		sideDeck = new CardList();
		scrollPane_2.setViewportView(sideDeck);
		
		scrollPane_3 = new JScrollPane();
		scrollPane_3.setBounds(10, 146, 210, 89);
		add(scrollPane_3);
		
		extraDeck = new CardList();
		scrollPane_3.setViewportView(extraDeck);
		
		lblExtraDeck = new JLabel("Extra Deck");
		lblExtraDeck.setBounds(10, 131, 210, 14);
		add(lblExtraDeck);
		mainDeck.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if(e.getValueIsAdjusting())
                    return;
                else{
                	CardInfo card = mainDeck.getSelectedValue();
                	if(card != null)
                		loadCardInfo(card);
                }
            }
          });
		extraDeck.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if(e.getValueIsAdjusting())
                    return;
                else{
                	CardInfo card = extraDeck.getSelectedValue();
                	if(card != null)
                		loadCardInfo(card);
                }
            }
          });
		sideDeck.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if(e.getValueIsAdjusting())
                    return;
                else{
                	CardInfo card = sideDeck.getSelectedValue();
                	if(card != null)
                		loadCardInfo(card);
                }
            }
          });
		
		setCardImage(AppGlobals.launcherConfig.launcherDir + "textures/cover.jpg");
		
	}
	void loadCardInfo(CardInfo card){
		setCardImage(AppGlobals.launcherConfig.launcherDir + "pics/" + card.getId() +".jpg");
		cardName.setText(card.getName());
		cardText.setText("");
		printText(card.getCardTypes() + " ");
		printText("\n");
        if (card.hasType(CardType.Monster)){
            String level = "";
            for (int i = 0; i < card.getLevel(); i++){
                level = level + "*";
            }
            printText(card.getCardRace());
            printText("\n");
            printText((card.hasType(CardType.Xyz) ? "Rank " : "Level ") + card.getLevel() + " " +
                "[" + level + "] " + ((card.getAtk() == -2) ? "?" : 
                 card.getAtk()) + "/" + ((card.getDef() == -2) ? "?" : card.getDef()));
            printText("\n");
        }
        else
        {
        	printText("\n");
        }
        
        printText(card.getDescription());
        cardText.setCaretPosition(0);
	}
	public void loadDeck(File deck){
		mainDeck.clearCards();
		sideDeck.clearCards();
	    BufferedReader file = null;
	    boolean isSideDeck = false;
	    boolean isExtraDeck = false;
	    try {
	    	file = new BufferedReader(new FileReader(deck));
	    
	        ArrayList<String> cardids = new ArrayList<String>();
	        String line = file.readLine();

	        while (line != null) {
	        	cardids.add(line);
	            line = file.readLine();
	        }
	        for(String id: cardids){
	        	if(id.startsWith("#"))
	        		if(id.startsWith("#extra")){
	        			isExtraDeck = true;
	        			continue;
	        		}else continue;
	        	if(id.startsWith("!")){
	        		isSideDeck = true;
	        		continue;
	        	}
	        	CardInfo card = CardManager.fromId(Integer.parseInt(id));
	        	if(card != null){
	        		if(isSideDeck)
	        			sideDeck.addCard(card);
	        		else if(isExtraDeck)
	        			extraDeck.addCard(card);
	        		else
	        			mainDeck.addCard(card);
	        	}
	        }
	        
	    } catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(file != null){
				try {
					file.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	    }
		//mainDeck.loadDeck(deck);
	}
	void setCardImage(String file){
		File cover = new File(file);
		if(cover.exists()){
				cardImage.setIcon(rescaleImage(cover,cardImage.getWidth(),cardImage.getHeight()));
		}
	}
	public String buildDeckList(){
		StringBuilder deckList = new StringBuilder();
		deckList.append("-- Main Deck -- \n");
        for (int i = 0; i < mainDeck.getModel().getSize(); i++) {
            CardInfo item = mainDeck.getModel().getElementAt(i);
            if(item != null)
            	deckList.append(item.getName() + " x" + item.count + "\n");
        }
        deckList.append("\n");
		deckList.append("-- Extra Deck -- \n");
        for (int i = 0; i < extraDeck.getModel().getSize(); i++) {
            CardInfo item = extraDeck.getModel().getElementAt(i);
            if(item != null)
            	deckList.append(item.getName() + " x" + item.count + "\n");
        }
        deckList.append("\n");
		deckList.append("-- Side Deck -- \n");
        for (int i = 0; i < sideDeck.getModel().getSize(); i++) {
            CardInfo item = sideDeck.getModel().getElementAt(i);
            if(item != null)
            	deckList.append(item.getName() + " x" + item.count + "\n");
        }	
		
		return deckList.toString();
	}
	public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth)
	{
	    int newHeight = 0, newWidth = 0;
	    int priorHeight = 0, priorWidth = 0;
	    BufferedImage image = null;
	    ImageIcon sizeImage;

	    try {
	           image = ImageIO.read(source);
	    } catch (Exception e) {

	            e.printStackTrace();
	            System.out.println("Picture upload attempted & failed");
	    }

	    sizeImage = new ImageIcon(image);

	    if(sizeImage != null)
	    {
	        priorHeight = sizeImage.getIconHeight(); 
	        priorWidth = sizeImage.getIconWidth();
	    }

	    if((float)priorHeight/(float)priorWidth > (float)maxHeight/(float)maxWidth)
	    {
	        newHeight = maxHeight;
	        newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight);
	    }
	    else 
	    {
	        newWidth = maxWidth;
	        newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth);
	    }

	    BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
	    Graphics2D g2 = resizedImg.createGraphics();

	    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	    g2.drawImage(image, 0, 0, newWidth, newHeight, null);
	    g2.dispose();

	    return (new ImageIcon(resizedImg));
	}
	private void printText(String text){
		try {
			
			StyledDocument doc = cardText.getStyledDocument();
			doc.insertString(doc.getLength(), text,null);
			
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
